package game.module.itemnew.dao;

import game.constants.GameConstant;
import game.constants.Position;
import game.module.itemnew.beans.ItemStorage;
import game.module.itemnew.beans.ItemStorage.Item;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

@Component
public class ItemCache {

	@Autowired
	private ItemDao itemDao;

	@Autowired
	public CacheManager cacheManager;

	/**
	 * 玩家上线时调用
	 * 
	 * @param heroId
	 */
	public void load(int heroId) {
		ItemStorage itemStore = itemDao.getItems(heroId);
		Cache cache = cacheManager.getCache(GameConstant.CACHE_GOODS);
		Map<Short, Item> bodyGoodMap = new ConcurrentHashMap<Short, Item>();
		Map<Short, Item> bagGoodMap = new ConcurrentHashMap<Short, Item>();
		cache.put(GameConstant.CACHE_GOODS_BAG + heroId, bagGoodMap);
		cache.put(GameConstant.CACHE_GOODS_BODY + heroId, bodyGoodMap);
		if (itemStore == null) {
			return;
		}
		for (Item goodsItem : itemStore.getItemList()) {
			short position = goodsItem.getPosition().shortValue();
			if ((position >= Position.BodyGoodsBeginPostion && position <= Position.BodyGoodsEndPostion)) {
				bodyGoodMap.put(position, goodsItem);
			} else if ((position >= Position.HorseGoodsBeginPostion && position <= Position.HorseGoodsEndPostion)) {
			} else if (position >= Position.BagGoodsBeginPostion && position <= Position.BagGoodsEndPostion) {
				bagGoodMap.put(position, goodsItem);
			} else if (position >= Position.StorageGoodsBeginPostion && position <= Position.StorageGoodsEndPostion) {
			} else if (position >= Position.StallGoodsBeginPostion && position <= Position.StallGoodsEndPostion) {
			}
		}
	}

	@SuppressWarnings("unchecked")
	public Map<Short, Item> getBodyGoodsMap(int heroId) {
		Cache cache = cacheManager.getCache(GameConstant.CACHE_GOODS);
		return (Map<Short, Item>) cache.get(GameConstant.CACHE_GOODS_BODY + heroId);
	}

	@SuppressWarnings("unchecked")
	public Map<Short, Item> getBagGoodsMap(int heroId) {
		Cache cache = cacheManager.getCache(GameConstant.CACHE_GOODS);
		return (Map<Short, Item>) cache.get(GameConstant.CACHE_GOODS_BAG + heroId).get();
	}

}
